var secondData = {};
var bundle = {
	"action" : "",
	"type" : "client",
	"content" : ""
};

(function(){
	//连接服务器
	var ws = new WebSocket("ws://"+window.location.hostname+":8003");
	//连接成功触发
	ws.onopen = function(){
		//alert("连接成功");
		bundle.action = "connect";
		fire(bundle);
	}
	//连接失败触发
	ws.onerror = function(){
		alert("连接失败");
	}
		
	ws.onmessage = function(msg){
		console.log(msg.data);
		var action = JSON.parse(msg.data);

		switch (action.type) {
			case "addSecond":

				draw(action.data);
				// statements_1
				break;
			case "setGroup":
				createGroupHtml(action.data);
				break;
			default:
				// statements_def
				break;
		}
	}

	function fire(bundle){
		bundle.type = "client";
		ws.send(JSON.stringify(bundle));
	}

})();
function createGroupHtml(arr) {
	secondData = {};
	var html = "";
	for(var i=0;i<arr.length;i++){
		var key = i+1;
		secondData[key] = 0;
		html += '<div class="wrap"><div class="text">'+arr[i]+'</div><div class="value" id="value'+(i+1)+'">';
		html += '<div class=" fontColor num " id="num'+(i+1)+'">0</div>';
		html += '</div></div>';
	}
	$("#box").html(html);
}


function draw(serverdata){
	var data = serverdata.split("|");
	var type = data[0];
	var sencond = data[1];
	secondData[type] = getValue(Number(secondData[type])) + getValue(Number(sencond));

	var unit = getUnit();

	for(var key in secondData){
		$("#num" + key).html(secondData[key]);
		$("#value" + key).height( (5 + secondData[key]*unit) );
	}
	$(".num").removeClass('active');
	var maxSecond = getHeightest();
	for(var i in secondData){
		if(secondData[i] == maxSecond){
			$("#value"+i).find(".num").addClass('active');
		}
	}
}

function getValue(v){
	var value = Number(v);
	if(isNaN(value)){
		return 0;
	}
	return value;
}
function getHeightest(){
	var heightest = 0;
	for(var key in secondData){
		if(heightest < getValue(secondData[key])){
			heightest = getValue(secondData[key]);
		}
	}
	return heightest;
}
var minUnit = 5;
function getUnit(){
	var heightest = getHeightest();
	if(heightest > 0){
		if(heightest < minUnit){
			heightest = minUnit;
		}
		return 350 / heightest;
	}
	return 2;
}
